package cn.sylinx.horm.resource.parse;

import cn.sylinx.horm.exception.HORMException;
import cn.sylinx.horm.resource.liquor.eval.Exprs;

import java.util.Collection;
import java.util.Map;

public abstract class SystemConditionParser {

    private static final String NOT_NULL_FLAG = "!!";

    private SystemConditionParser() {
    }

    public static boolean testCondition(String express, Map<String, Object> params) {

        if (params == null) {
            return false;
        }

        if (express == null) {
            return false;
        }

        express = express.trim();

        if (express.startsWith(NOT_NULL_FLAG)) {
            // 空判断
            String trueField = express.substring(NOT_NULL_FLAG.length()).trim();
            if (trueField.isEmpty()) {
                return false;
            }

            Object value = params.get(trueField);
            if (value == null) {
                return false;
            }

            // 如果是字符串，判断是否是空白字符串
            if (value instanceof String) {
                return !value.toString().isEmpty();
            }

            // 如果是collection，判断是否有元素
            if (value instanceof Collection) {
                return !((Collection<?>) value).isEmpty();
            }

            return true;
        }

        try {
            return (boolean) Exprs.eval(express, params);
        } catch (Exception e) {
            throw new HORMException(e);
        }
    }
}
